package com.zxd.service.impl;

import com.zxd.core.Constant;
import com.zxd.dao.ModuleDao;
import com.zxd.dao.RoleDao;
import com.zxd.dao.RoleModuleDao;
import com.zxd.entity.Module;
import com.zxd.entity.Role;
import com.zxd.entity.RoleModule;
import com.zxd.service.RoleModuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * roleModuleServiceImpl
 * Created by 奕恒 on 2017/2/20 21:54.
 */
@Service
public class RoleModuleServiceImpl implements RoleModuleService {

    @Autowired
    private RoleModuleDao roleModuleDao;

    @Autowired
    private ModuleDao moduleDao;

    @Autowired
    private RoleDao roleDao;

    @Override
    public List<RoleModule> findAll() {
        return roleModuleDao.findAll();
    }

    @Override
    public Page<RoleModule> find(int pageNum, int pageSize) {
        return roleModuleDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<RoleModule> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public RoleModule getById(int id) {
        return roleModuleDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        for (RoleModule roleModule : roleModuleDao.findListByRoleId(id)) {
            roleModuleDao.delete(roleModule.getId());
        }

        roleDao.delete(id);
    }

    @Override
    public RoleModule create(RoleModule roleModule) {
        return roleModuleDao.save(roleModule);
    }

    @Override
    public RoleModule update(RoleModule roleModule) {
        return roleModuleDao.save(roleModule);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public List<Module> findListByMasterId(Integer masterId) {
        StringBuilder str = new StringBuilder();
        List<Module> moduleList = new ArrayList<>();
        Module module;

        List<RoleModule> roleModuleList = roleModuleDao.findListByMasterId(masterId);

        for (RoleModule roleModule : roleModuleList) {
            module = roleModule.getModule();

            // 排除掉所有子模块
            if (!module.getParentId().equals(Constant.CHECK_STATUS_DEFAULT)) {
                continue;
            }

            if (!str.toString().contains(module.getName())) {
                str.append(module.getName());

                // 查询该模块的子模块信息
                module.setChildList(getChildList(roleModuleList, module.getId()));

                moduleList.add(module);
            }
        }

        return moduleList;
    }

    /**
     * 根据父级模块及管理员ID查询该管理员对应的一级菜单下的子菜单列表
     */
    private List<Module> getChildList(List<RoleModule> roleModuleList, Integer moduleId) {
        List<Module> moduleList = new ArrayList<>();

        for (RoleModule roleModule : roleModuleList) {
            if (roleModule.getModule().getParentId().equals(moduleId)) {
                moduleList.add(roleModule.getModule());
            }
        }

        return moduleList;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Map<String, Object>> getMenuByParams(HttpServletRequest request, Integer parentId) {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map;
        List<Module> finallyModuleList = new ArrayList<>();

        List<Module> moduleList = (List<Module>) request.getSession().getAttribute("moduleList");

        // 如果parentId为0，则代表是系统初始化时的默认加载项，此时只加载第一个主菜单的下级菜单
        if (parentId.equals(Constant.CHECK_STATUS_DEFAULT)) {
            finallyModuleList = moduleList.get(0).getChildList();
        } else {
            for (Module module : moduleList) {
                if (module.getId().equals(parentId)) {
                    finallyModuleList = module.getChildList();
                }
            }
        }

        for (Module module : finallyModuleList) {
            map = new HashMap<>();
            map.put("title", module.getName());
            map.put("icon", module.getIconUrl());
            map.put("href", module.getUrl());
            map.put("spread", false);

            list.add(map);
        }

        return list;
    }

    @Override
    public Integer savePower(Integer roleId, String name, String ids) {
        RoleModule temp;
        Module module;
        Role role = new Role();
        role.setId(roleId);

        for (RoleModule roleModule : roleModuleDao.findListByRoleId(role.getId())) {
            roleModuleDao.delete(roleModule.getId());
        }

        for (String s : ids.split(",")) {
            temp = new RoleModule();
            temp.setRole(role);

            module = moduleDao.findOne(Integer.parseInt(s));

            if (null == module) {
                continue;
            }

            temp.setModule(module);

            roleModuleDao.save(temp);
        }

        return 1;
    }

    @Override
    public List<Integer> getRoleModule(Integer roleId) {
        List<Integer> list = new ArrayList<>();

        for (RoleModule roleModule : roleModuleDao.findListByRoleId(roleId)) {
            if (!roleModule.getModule().getParentId().equals(0)) {
                list.add(roleModule.getModule().getId());
            }
        }

        return list;
    }

    @Override
    @Transactional
    public Integer batchDel(String ids) {
        for (String s : ids.split(",")) {
            deleteById(Integer.parseInt(s));
        }

        return 1;
    }

    @Override
    public List<RoleModule> paramsByMasterId(Integer masterId) {
        return roleModuleDao.findListByMasterId(masterId);
    }
}